<template>
  <BoTable
    ref="tableRef"
    :request="fetchList"
    :columns="columns"
    :row-selection="rowSelection"
    row-key="id"
    :auto-load="false"
  >
    <template #leftContainer>
      <DeptTree
        v-model:roleList="roleList"
        v-model:group-id="groupId"
        @search="onSearch"
      />
    </template>
    <template #toolbars>
      <Space>
        <Button @click="onAdd" code="roleGroupItem:add">新增</Button>
        <Button
          :disabled="!selectKeys?.length"
          @click="onDelete(null)"
          code="roleGroupItem:delete"
          >删除</Button
        >
      </Space>
    </template>
    <template #enable="{ record }">
      <Switch
        :checked="record.enable"
        checked-value="0"
        un-checked-value="1"
        @change="(checked) => onChangeStatus(checked as string, record)"
      ></Switch>
    </template>
  </BoTable>
  <FormModal :columns="items"> </FormModal>
</template>
<route lang="json">
{
  "name": "group",
  "meta": {
    "title": "接收对象分组"
  }
}
</route>
<script setup lang="tsx">
import { computed, ref } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { formatTree, treeToArray, treeToEnum } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, Input, Modal, Space, Switch, message } from 'ant-design-vue';
import {
  createRoleGroupUser,
  deleteRoleGroupUser,
  fetchRoleGroupUser,
  fetchUsers,
  getDeptSelect,
  updateRoleGroupUser,
} from './api';
import DeptTree from './components/DeptTree.vue';

const tableRef = ref();

const fetchList = (params: Record<string, any>) => {
  return fetchRoleGroupUser({ ...params, groupId: groupId.value });
};
const roleList = ref([]);
const groupId = ref('');
const onSearch = () => {
  tableRef.value.refresh();
};

const dictArr = ['sys_user_sex', 'use_status'];
const { sysUserSexEnum, sysUserSexOptions, useStatusEnum } = useDicts(dictArr);

// 用户信息
const usersOptions = ref<any[]>([]);
const userEnum = ref<Record<string, any>>({});

const departmentTree = ref([]);
const departmentOptions = ref([]);
const departmentEnum = ref<Record<string, any>>({});
const init = () => {
  fetchUsers().then((res) => {
    for (const user of res.data as any[]) {
      userEnum.value[user.userId] = user;
      usersOptions.value.push({ label: user.nickName, value: user.userId });
    }
  });
  // 部门信息
  getDeptSelect().then((res) => {
    departmentTree.value = formatTree(res.data, {
      label: 'label',
      value: 'id',
    });
    departmentOptions.value = treeToArray(res.data, { value: 'id' });
    departmentEnum.value = treeToEnum(res.data, { id: 'id', text: 'label' });
  });
};

init();

const selectKeys = ref<number[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => ({
  selectedRowKeys: selectKeys.value,
  onChange(values) {
    selectKeys.value = values as number[];
  },
}));

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '单位',
    dataIndex: 'deptId',
    valueEnum: departmentEnum.value,
    valueType: 'select',
  },
  {
    title: '姓名',
    dataIndex: 'name',
  },
  {
    title: '性别',
    dataIndex: 'sex',
    hideInSearch: true,
    valueEnum: sysUserSexEnum.value,
  },
  {
    title: '电话',
    dataIndex: 'phone',
    hideInSearch: true,
  },
  {
    title: '微信ID',
    dataIndex: 'wx',
    hideInSearch: true,
    ellipsis: true,
  },
  {
    title: '是否启用',
    dataIndex: 'enable',
    valueEnum: useStatusEnum.value,
    valueType: 'select',
    width: 80,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    width: 80,
    fixed: 'right',
    actions: [
      {
        text: '详情',
        onClick(record) {
          onView(record);
        },
      },
      {
        text: '删除',
        onClick(record) {
          onDelete(record);
        },
      },
    ],
  },
]);

const items = computed<BoFormProps['columns']>(() => [
  {
    title: '姓名',
    valueType: 'select',
    dataIndex: 'userId',
    formItemProps: {
      rules: [{ required: true, message: '请选择用户', trigger: 'blur' }],
    },
    fieldProps: {
      pplaceholder: '请选择用户',
      options: usersOptions.value,
    },
  },
  {
    title: '部门',
    valueType: 'treeSelect',
    dataIndex: 'deptId',
    fieldProps: {
      disabled: true,
      treeData: departmentTree.value,
    },

    render(state) {
      state.sex = userEnum.value[state.userId]?.sex || state.sex;
      state.phone = userEnum.value[state.userId]?.phone || state.phone;
      state.deptId =
        departmentEnum.value[userEnum.value[state.userId]?.deptId]?.text;
      return <Input value={state.deptId}></Input>;
    },
  },
  {
    title: '电话',
    valueType: 'input',
    dataIndex: 'phone',
    fieldProps: {
      placeholder: '请输入电话',
    },
  },
  {
    title: '性别',
    valueType: 'select',
    dataIndex: 'sex',
    fieldProps: {
      placeholder: '请选择性别',
      options: sysUserSexOptions.value as any,
    },
  },
]);

const { FormModal, open } = useFormModal({
  size: 'small',
});

const formatParams = (params: any) => {
  const { userId } = params;
  const { nickName: name, userName, wxUserId } = userEnum.value[userId];

  return {
    ...params,
    name,
    userName,
    wx: wxUserId,
  };
};

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {},
    request: async (params: any): Promise<any> => {
      params.deptId = userEnum.value[params.userId]?.deptId;
      params.groupId = groupId.value;
      console.log(params.deptId, 'params');
      await createRoleGroupUser(formatParams(params));
      tableRef.value.refresh();
    },
  });
};

const onView = async (record: any) => {
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: record,
    request: async (params: any): Promise<any> => {
      params.deptId = userEnum.value[params.userId]?.deptId;
      params.groupId = groupId.value;
      await updateRoleGroupUser({
        ...formatParams(params),
        id: record.id,
      });
      tableRef.value.refresh();
    },
  });
};

const onDelete = async (record: any) => {
  console.log(record);
  const ids = record ? record.id : selectKeys.value.join();
  if (!ids) return message.info('请选择要删除的数据');
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选中项数据吗？`,
    onOk: async () => {
      await deleteRoleGroupUser(ids);
      selectKeys.value = [];
      tableRef.value.refresh();
      message.success('操作成功');
    },
  });
};

const onChangeStatus = (checked: string, record: any) => {
  const { id, name } = record;
  Modal.confirm({
    title: '系统提示',
    content: `确认要${checked === '1' ? '停用' : '启用'}${name}用户吗？`,
    onOk: async () => {
      await updateRoleGroupUser({
        id,
        enable: checked as '0' | '1',
      });
      tableRef.value.search();
    },
  });
};
</script>
